
class TreeNode {
    val: number
    left: TreeNode | null
    right: TreeNode | null
    constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
        this.val = (val===undefined ? 0 : val)
        this.left = (left===undefined ? null : left)
        this.right = (right===undefined ? null : right)
    }
}

const tree0 = new TreeNode(0)
const tree3 = new TreeNode(3)
const tree8 = new TreeNode(8)
const tree2 = new TreeNode(2,null,tree3)
const tree1 = new TreeNode(1,tree0,tree2)
const tree7 = new TreeNode(7,null,tree8)
const tree5 = new TreeNode(5)
const tree6 = new TreeNode(6,tree5,tree7)
const tree4 = new TreeNode(4,tree1,tree6)

function bstToGst(root: TreeNode | null): TreeNode | null {
    // let sum:number = 0
    someFun(root, 0)
    return root
};

function someFun(root: TreeNode | null, sum: number) {
    if(root?.right) {
        sum = someFun(root.right, sum)
    }
    if(root?.val != undefined) {
        sum += root.val
        root.val = sum
        console.log(root.val,sum)
    }
    if(root?.left) {
        sum = someFun(root.left, sum)
    }
    return sum
}

console.log(bstToGst(tree4))